package javabase.demo02;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

public class MapPractice {
    public static void main(String[] args) {
        // HashMap - 最常用的Map实现
        Map<String, Integer> hashMap = new HashMap<>();
        // 添加键值对
        hashMap.put("Apple", 10);
        hashMap.put("Banana", 5);
        hashMap.put("Orange", 8);
        hashMap.put("Apple", 15); // 更新已有键的值

        System.out.println("HashMap: " + hashMap);

        // 访问值
        System.out.println("Apple的数量: " + hashMap.get("Apple"));
        System.out.println("包含Banana键? " + hashMap.containsKey("Banana"));
        System.out.println("包含值10? " + hashMap.containsValue(10));

        // 遍历HashMap
        System.out.println("=== 遍历HashMap ===");
        for (String key: hashMap.keySet()){
            System.out.println("Key: " + key + ", Value: " + hashMap.get(key));
        }

        for (Integer value : hashMap.values()) {
            System.out.println("Value: " + value);
        }

        for (Map.Entry<String, Integer> entry : hashMap.entrySet()) {
            System.out.println("Entry: " + entry.getKey() + " => " + entry.getValue());
        }

        // 4. forEach方法 (Java 8+)
        hashMap.forEach((k, v) -> System.out.println("ForEach: " + k + " => " + v));

        // 访问顺序的LinkedHashMap (LRU缓存基础)
        Map<String, Integer> accessOrderMap = new LinkedHashMap<>(16, 0.75f, true);
        accessOrderMap.put("A", 1);
        accessOrderMap.put("B", 2);
        accessOrderMap.put("C", 3);

        // 访问元素B，它会被移动到末尾
        accessOrderMap.get("B");
        System.out.println("访问顺序LinkedHashMap: " + accessOrderMap);

        // TreeMap - 基于红黑树，按键排序
        Map<String, Integer> treeMap = new TreeMap<>();
        treeMap.put("Orange", 3);
        treeMap.put("Apple", 1);
        treeMap.put("Banana", 2);

        System.out.println("TreeMap(按键排序): " + treeMap);

        // 自定义排序
        Map<String, Integer> reverseTreeMap = new TreeMap<>(Comparator.reverseOrder());
        reverseTreeMap.put("Orange", 3);
        reverseTreeMap.put("Apple", 1);
        reverseTreeMap.put("Banana", 2);

        System.out.println("TreeMap(逆序): " + reverseTreeMap);

        // ConcurrentHashMap - 线程安全的HashMap
        Map<String, Integer> concurrentMap = new ConcurrentHashMap<>();
        concurrentMap.put("A", 1);
        concurrentMap.put("B", 2);
        concurrentMap.put("C", 3);

        System.out.println("ConcurrentHashMap: " + concurrentMap);
    }
}
